/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */

/*
 * JFrmMain.java
 *
 * Created on Mar 3, 2009, 11:25:40 PM
 */
package org.grid.nodegui;

import java.awt.AWTException;
import java.awt.Image;
import java.awt.MenuItem;
import java.awt.PopupMenu;
import java.awt.SystemTray;
import java.awt.Toolkit;
import java.awt.TrayIcon;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.io.FileNotFoundException;
import java.io.PrintWriter;
import javax.swing.Icon;
import javax.swing.ImageIcon;
import org.grid.gui.LookAndFeelManager;
import org.grid.gui.MessageBox;
import org.grid.gui.TextMessageBox;
import org.grid.model.rmi.CalculatorObserver;
import org.grid.model.rmi.LogCalculatorServer;
import org.grid.util.ExceptionHelper;

/**
 *
 * @author wellington
 */
public class JFrmMain extends javax.swing.JDialog implements CalculatorObserver {

    private LogCalculatorServer server;
    private TrayIcon trayIcon;

    /** Creates new form JFrmMain */
    public JFrmMain() {
        LookAndFeelManager.initLookAndFeel();
        initComponents();        
        initServer();
    }

    @SuppressWarnings("unchecked")
    // <editor-fold defaultstate="collapsed" desc="Generated Code">//GEN-BEGIN:initComponents
    private void initComponents() {
        java.awt.GridBagConstraints gridBagConstraints;

        mnuTrayIcon = new javax.swing.JPopupMenu();
        mniClose = new javax.swing.JMenuItem();
        pnlCenter = new javax.swing.JPanel();
        pnlConfiguration = new javax.swing.JPanel();
        lblListenURL = new javax.swing.JLabel();
        txtListenURL = new javax.swing.JTextField();
        lblStatus = new javax.swing.JLabel();
        lblStatusValue = new javax.swing.JLabel();
        btnActivate = new javax.swing.JButton();
        lblPackageIn = new javax.swing.JLabel();
        lblPackageOut = new javax.swing.JLabel();
        txtPackageIn = new javax.swing.JTextField();
        txtPackageOut = new javax.swing.JTextField();
        pnlBottom = new javax.swing.JPanel();
        btnOK = new javax.swing.JButton();
        pnlTop = new javax.swing.JPanel();
        lblTitle = new javax.swing.JLabel();

        mniClose.setText("jMenuItem1");
        mniClose.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                mniCloseActionPerformed(evt);
            }
        });
        mnuTrayIcon.add(mniClose);

        setTitle("Servidor de Processamento");
        setResizable(false);

        pnlConfiguration.setBorder(javax.swing.BorderFactory.createTitledBorder(null, "Configuração", javax.swing.border.TitledBorder.DEFAULT_JUSTIFICATION, javax.swing.border.TitledBorder.DEFAULT_POSITION, new java.awt.Font("Tahoma", 1, 11))); // NOI18N
        pnlConfiguration.setOpaque(false);
        pnlConfiguration.setLayout(new java.awt.GridBagLayout());

        lblListenURL.setFont(new java.awt.Font("Tahoma", 1, 11));
        lblListenURL.setText("URL:");
        gridBagConstraints = new java.awt.GridBagConstraints();
        gridBagConstraints.anchor = java.awt.GridBagConstraints.EAST;
        gridBagConstraints.insets = new java.awt.Insets(3, 3, 3, 3);
        pnlConfiguration.add(lblListenURL, gridBagConstraints);

        txtListenURL.setEditable(false);
        gridBagConstraints = new java.awt.GridBagConstraints();
        gridBagConstraints.gridwidth = 2;
        gridBagConstraints.fill = java.awt.GridBagConstraints.HORIZONTAL;
        gridBagConstraints.weightx = 1.0;
        gridBagConstraints.insets = new java.awt.Insets(6, 6, 6, 6);
        pnlConfiguration.add(txtListenURL, gridBagConstraints);

        lblStatus.setFont(new java.awt.Font("Tahoma", 1, 11));
        lblStatus.setText("Status:");
        gridBagConstraints = new java.awt.GridBagConstraints();
        gridBagConstraints.gridx = 0;
        gridBagConstraints.gridy = 1;
        gridBagConstraints.anchor = java.awt.GridBagConstraints.EAST;
        gridBagConstraints.insets = new java.awt.Insets(3, 3, 3, 3);
        pnlConfiguration.add(lblStatus, gridBagConstraints);

        lblStatusValue.setText("[STATUS]");
        gridBagConstraints = new java.awt.GridBagConstraints();
        gridBagConstraints.gridx = 1;
        gridBagConstraints.gridy = 1;
        gridBagConstraints.fill = java.awt.GridBagConstraints.HORIZONTAL;
        gridBagConstraints.insets = new java.awt.Insets(6, 6, 6, 6);
        pnlConfiguration.add(lblStatusValue, gridBagConstraints);

        btnActivate.setBackground(new java.awt.Color(153, 153, 153));
        btnActivate.setText("Reiniciar");
        btnActivate.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                btnActivateActionPerformed(evt);
            }
        });
        gridBagConstraints = new java.awt.GridBagConstraints();
        gridBagConstraints.gridx = 2;
        gridBagConstraints.gridy = 1;
        gridBagConstraints.anchor = java.awt.GridBagConstraints.EAST;
        gridBagConstraints.insets = new java.awt.Insets(6, 6, 6, 6);
        pnlConfiguration.add(btnActivate, gridBagConstraints);

        lblPackageIn.setFont(new java.awt.Font("Tahoma", 1, 11));
        lblPackageIn.setText("Pacotes Recebidos:");
        gridBagConstraints = new java.awt.GridBagConstraints();
        gridBagConstraints.gridx = 0;
        gridBagConstraints.gridy = 2;
        gridBagConstraints.fill = java.awt.GridBagConstraints.HORIZONTAL;
        gridBagConstraints.anchor = java.awt.GridBagConstraints.EAST;
        gridBagConstraints.insets = new java.awt.Insets(3, 3, 3, 3);
        pnlConfiguration.add(lblPackageIn, gridBagConstraints);

        lblPackageOut.setFont(new java.awt.Font("Tahoma", 1, 11));
        lblPackageOut.setText("Pacotes Enviados:");
        gridBagConstraints = new java.awt.GridBagConstraints();
        gridBagConstraints.gridx = 0;
        gridBagConstraints.gridy = 3;
        gridBagConstraints.anchor = java.awt.GridBagConstraints.EAST;
        gridBagConstraints.insets = new java.awt.Insets(3, 3, 3, 3);
        pnlConfiguration.add(lblPackageOut, gridBagConstraints);

        txtPackageIn.setColumns(10);
        txtPackageIn.setEditable(false);
        txtPackageIn.setText("0");
        gridBagConstraints = new java.awt.GridBagConstraints();
        gridBagConstraints.gridx = 1;
        gridBagConstraints.gridy = 2;
        gridBagConstraints.gridwidth = 2;
        gridBagConstraints.fill = java.awt.GridBagConstraints.HORIZONTAL;
        gridBagConstraints.insets = new java.awt.Insets(6, 6, 6, 6);
        pnlConfiguration.add(txtPackageIn, gridBagConstraints);

        txtPackageOut.setColumns(10);
        txtPackageOut.setEditable(false);
        txtPackageOut.setText("0");
        gridBagConstraints = new java.awt.GridBagConstraints();
        gridBagConstraints.gridx = 1;
        gridBagConstraints.gridy = 3;
        gridBagConstraints.gridwidth = 2;
        gridBagConstraints.fill = java.awt.GridBagConstraints.HORIZONTAL;
        gridBagConstraints.insets = new java.awt.Insets(6, 6, 6, 6);
        pnlConfiguration.add(txtPackageOut, gridBagConstraints);

        javax.swing.GroupLayout pnlCenterLayout = new javax.swing.GroupLayout(pnlCenter);
        pnlCenter.setLayout(pnlCenterLayout);
        pnlCenterLayout.setHorizontalGroup(
            pnlCenterLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(pnlCenterLayout.createSequentialGroup()
                .addContainerGap()
                .addComponent(pnlConfiguration, javax.swing.GroupLayout.DEFAULT_SIZE, 415, Short.MAX_VALUE)
                .addContainerGap())
        );
        pnlCenterLayout.setVerticalGroup(
            pnlCenterLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(pnlCenterLayout.createSequentialGroup()
                .addContainerGap()
                .addComponent(pnlConfiguration, javax.swing.GroupLayout.DEFAULT_SIZE, 185, Short.MAX_VALUE)
                .addContainerGap())
        );

        getContentPane().add(pnlCenter, java.awt.BorderLayout.CENTER);

        pnlBottom.setLayout(new java.awt.FlowLayout(java.awt.FlowLayout.RIGHT));

        btnOK.setBackground(new java.awt.Color(153, 153, 153));
        btnOK.setText("OK");
        btnOK.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                btnOKActionPerformed(evt);
            }
        });
        pnlBottom.add(btnOK);

        getContentPane().add(pnlBottom, java.awt.BorderLayout.SOUTH);

        pnlTop.setLayout(new java.awt.BorderLayout());

        lblTitle.setFont(new java.awt.Font("Tahoma", 1, 18)); // NOI18N
        lblTitle.setHorizontalAlignment(javax.swing.SwingConstants.LEFT);
        lblTitle.setIcon(new javax.swing.ImageIcon(getClass().getResource("/org/grid/resources/misc.png"))); // NOI18N
        lblTitle.setText("Servidor de Processamento");
        lblTitle.setOpaque(true);
        pnlTop.add(lblTitle, java.awt.BorderLayout.PAGE_START);

        getContentPane().add(pnlTop, java.awt.BorderLayout.NORTH);

        java.awt.Dimension screenSize = java.awt.Toolkit.getDefaultToolkit().getScreenSize();
        setBounds((screenSize.width-443)/2, (screenSize.height-322)/2, 443, 322);
    }// </editor-fold>//GEN-END:initComponents

    // <editor-fold defaultstate="collapsed" desc="methods">
    private void initServer() {
        try {
            if (server == null) {
                server = new LogCalculatorServer();
            }
            server.stopServer();
            boolean status = server.startServer("org.grid.model.calculate.SimpleCalculatorOperation");
            initTrayIcon("Porta: " + server.getNode().getPort());
            if (status) {
                messageTrayIcon("Servidor iniciado na porta " + server.getNode().getPort(), status);
                lblStatusValue.setText("Servidor iniciado");
                txtListenURL.setText(server.getNode().toString());
            } else {
                messageTrayIcon("Erro ao iniciar servidor", status);
                lblStatusValue.setText("Erro ao iniciar servidor");
                txtListenURL.setText(null);
            }
            server.getLogCalculatorImpl().add(this);
        } catch (Exception e) {            
            TextMessageBox.showError(null, "Erro ao iniciar servidor", ExceptionHelper.getStack(e));
        }
    }
    // </editor-fold>

    // <editor-fold defaultstate="collapsed" desc="events">
    private void mniCloseActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_mniCloseActionPerformed
        this.dispose();
        System.exit(0);
    }//GEN-LAST:event_mniCloseActionPerformed

    private void btnActivateActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_btnActivateActionPerformed
        initServer();
}//GEN-LAST:event_btnActivateActionPerformed

    private void btnOKActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_btnOKActionPerformed
        setVisible(false);
}//GEN-LAST:event_btnOKActionPerformed

    private void trayIconActionPerformed(ActionEvent evt) {
        this.setVisible(!this.isVisible());
    }
    // </editor-fold>

    // <editor-fold defaultstate="collapsed" desc="tray">
    private void initTrayIcon(String text) {
        if (!SystemTray.isSupported()|| trayIcon!=null) {
            return;
        }
        SystemTray systemTray = SystemTray.getSystemTray();
        Image image = Toolkit.getDefaultToolkit().getImage(getClass().getResource("/org/grid/resources/server.png"));
        trayIcon = new TrayIcon(image, text);
        trayIcon.setImageAutoSize(true);
        trayIcon.addActionListener(new java.awt.event.ActionListener() {

            public void actionPerformed(java.awt.event.ActionEvent evt) {
                trayIconActionPerformed(evt);
            }
        });
        trayIcon.setPopupMenu(initPopupMenu());
        try {
            systemTray.add(trayIcon);
        } catch (AWTException e) {
            System.err.println(e);
        }

    }

    private PopupMenu initPopupMenu() {
        PopupMenu popupTray = new PopupMenu();
        MenuItem menuItemInit = new MenuItem("Reiniciar");
        menuItemInit.addActionListener(new ActionListener() {

            public void actionPerformed(ActionEvent e) {
                initServer();
            }
        });
        MenuItem menuItemShow = new MenuItem("Mostrar");
        menuItemShow.addActionListener(new ActionListener() {

            public void actionPerformed(ActionEvent e) {
                trayIconActionPerformed(e);
            }
        });
        MenuItem menuItemClose = new MenuItem("Sair");
        menuItemClose.addActionListener(new ActionListener() {

            public void actionPerformed(ActionEvent e) {
                System.exit(0);
            }
        });
        popupTray.add(menuItemInit);
        popupTray.add(menuItemShow);
        popupTray.addSeparator();
        popupTray.add(menuItemClose);
        return popupTray;
    }

    private void messageTrayIcon(String message, boolean connected) {
        Image image = null;
        if (connected) {
            image = Toolkit.getDefaultToolkit().getImage(getClass().getResource("/org/grid/resources/server.png"));
        } else {
            image = Toolkit.getDefaultToolkit().getImage(getClass().getResource("/org/grid/resources/server_down.png"));
        }
        trayIcon.setImage(image);
        lblStatusValue.setIcon(new ImageIcon(image));
        trayIcon.displayMessage("Sistema Distribuido", message, TrayIcon.MessageType.INFO);
    }
    // </editor-fold>

    // Variables declaration - do not modify//GEN-BEGIN:variables
    private javax.swing.JButton btnActivate;
    private javax.swing.JButton btnOK;
    private javax.swing.JLabel lblListenURL;
    private javax.swing.JLabel lblPackageIn;
    private javax.swing.JLabel lblPackageOut;
    private javax.swing.JLabel lblStatus;
    private javax.swing.JLabel lblStatusValue;
    private javax.swing.JLabel lblTitle;
    private javax.swing.JMenuItem mniClose;
    private javax.swing.JPopupMenu mnuTrayIcon;
    private javax.swing.JPanel pnlBottom;
    private javax.swing.JPanel pnlCenter;
    private javax.swing.JPanel pnlConfiguration;
    private javax.swing.JPanel pnlTop;
    private javax.swing.JTextField txtListenURL;
    private javax.swing.JTextField txtPackageIn;
    private javax.swing.JTextField txtPackageOut;
    // End of variables declaration//GEN-END:variables

    public void notify(long packageIn, long packageOut) {
        txtPackageIn.setText(String.valueOf(packageIn));
        txtPackageOut.setText(String.valueOf(packageOut));
    }
}
